//
//  SkyTcpCmdDataPack.m
//  BLEKiSDK
//
//  Created by wulanzhou on 16/3/16.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "SkyTcpCmdDataPack.h"

@implementation SkyTcpCmdDataPack

- (id)init{

    if (self=[super init]) {
        
        //(1)短数据区
        self.packVersion=0xdf;
        self.ascSign=0x55;
        
        //(2)命令区
        self.mCmd=0x01;
        self.subCmd=0x01;
        
        //(3)数据区
        
        //psn 4位随便
        Byte psnBytes[4];
        psnBytes[0]=0x01;
        psnBytes[1]=0x02;
        psnBytes[2]=0x03;
        psnBytes[3]=0x04;
        
        self.packSN=[[NSData alloc] initWithBytes:psnBytes length:sizeof(psnBytes)];
        
        //APKSN
        Byte apksnBytes[2];
        apksnBytes[0]=0x07;
        apksnBytes[1]=0xD1;
        
        self.apkSN=[[NSData alloc] initWithBytes:apksnBytes length:sizeof(apksnBytes)];
        

        apksnBytes[0]=0x03;
        apksnBytes[1]=0xE9;
        self.appSN=[[NSData alloc] initWithBytes:apksnBytes length:sizeof(apksnBytes)];
        
        //(4)mac区
        Byte macBytes[4];
        macBytes[0]=0xfe;
        macBytes[1]=0xfe;
        macBytes[2]=0xfe;
        macBytes[3]=0xfe;
        
        self.macData=[[NSData alloc] initWithBytes:macBytes length:sizeof(macBytes)];
        
    }
    return self;
}

- (id)initWithDataPack:(NSData *)dataPack{

    if (self=[super init]) {
     
        
        //(1)短数据区
        self.totalDataPackLen=dataPack.length;
        
        //dataPack=[dataPack subdataWithRange:NSMakeRange(4, dataPack.length-4)];
        Byte *b=(Byte *)[dataPack bytes];
        self.packVersion=b[0];
        self.ascSign=b[1];
        
        //(2)命令区
        dataPack=[dataPack subdataWithRange:NSMakeRange(2, dataPack.length-2)];
        
        self.cardData=[dataPack subdataWithRange:NSMakeRange(0, 8)];
        
        dataPack=[dataPack subdataWithRange:NSMakeRange(8, dataPack.length-8)];
        b=(Byte *)[dataPack bytes];
        
        self.mCmd=b[0];
        self.subCmd=b[1];
        
        dataPack=[dataPack subdataWithRange:NSMakeRange(2, dataPack.length-2)];
        //(3)数据区
        
        
        //a.数据区长度
        NSData *uDataLen=[dataPack subdataWithRange:NSMakeRange(0, 2)];
        short nLen = 0;
        [uDataLen getBytes:(void *)&nLen length:2];
        nLen = ntohs(nLen);
        self.udataPackLen=nLen;
        
        //b.数据区
        dataPack=[dataPack subdataWithRange:NSMakeRange(2, dataPack.length-2)];
        
        self.packSN=[dataPack subdataWithRange:NSMakeRange(0, 4)];
        dataPack=[dataPack subdataWithRange:NSMakeRange(4, dataPack.length-4)];
        
        
        
        self.apkSN=[dataPack subdataWithRange:NSMakeRange(0, 2)];
        dataPack=[dataPack subdataWithRange:NSMakeRange(2, dataPack.length-2)];
        
        
        
        self.appSN=[dataPack subdataWithRange:NSMakeRange(0, 2)];
        dataPack=[dataPack subdataWithRange:NSMakeRange(2, dataPack.length-2)];
        
        
        
        //状态处理
        self.stateData=[dataPack subdataWithRange:NSMakeRange(0, 2)];
        dataPack=[dataPack subdataWithRange:NSMakeRange(2, dataPack.length-2)];
        
        
        
        //数据命令
        self.cmdData=[dataPack subdataWithRange:NSMakeRange(0, dataPack.length-4)];
        dataPack=[dataPack subdataWithRange:NSMakeRange(self.cmdData.length, dataPack.length-self.cmdData.length)];
        
        //mac区
        self.macData=dataPack;

        
    }
    return self;
}

/**
 *  tcp数据包解码处理
 *
 *  @param dataPack 解码数据包
 *
 *  @return
 */
+ (id)decodeWithDataPack:(NSData *)dataPack{

    if (dataPack&&dataPack.length>0) {
        
        return [[self alloc] initWithDataPack:dataPack];
    }
    return nil;
}

- (NSData *)encodeDataPack{

    NSMutableData *mulData=[NSMutableData dataWithCapacity:1024];
    //短包区
    [mulData appendData:[self GetAllShortDataPack]];
    //命令区
    [mulData appendData:[self GetCmdDataPack]];
    //数据区
    [mulData appendData:[self GetAllDataAreaDataPack]];
    
    return mulData;
}


/**
 *  下载ki需要添加数据
 *
 *  @param cardIdData CardID号
 *  @param imsiData   IMSI号(服务器下载取得的imsi)
 */
- (void)downloadKiWithCardIDData:(NSData *)cardIdData withIMSIData:(NSData *)imsiData{

    self.cardData=cardIdData;
    
    //申请命令参数
    NSMutableData *mulData=[NSMutableData dataWithCapacity:1024];
    
    //(1)区分标识 910180作为区分的 (卡类型—为KI实体卡),区分是KI申请，还是远程卡申请
    Byte diff[3];
    diff[0]=0x91;
    diff[1]=0x01;
    diff[2]=0x80;
    [mulData appendBytes:diff length:sizeof(diff)];
    
    //(2)0x98＋imsi数据长度＋imsi数据
    Byte b[2];
    b[0]=0x98;
    b[1]=(Byte)(imsiData.length&0xff);
    [mulData appendBytes:b length:sizeof(b)];
    [mulData appendData:imsiData];
    
    self.cmdData=mulData;
    
    NSUInteger uLen=self.packSN.length+self.apkSN.length+self.appSN.length+mulData.length;
    
    //数据区长度
    self.udataPackLen=uLen;
    
    //总包长度
    self.totalDataPackLen=[self GetPartShortDataPack].length+[self GetCmdDataPack].length+[self GetAllDataAreaDataPack].length;
}

/**
 *  释放ki数据
 *
 *  @param cardIdData CardID号
 *  @param imsiData   IMSI号 (ble释放sim卡时取得的imsi)
 */
- (void)releaseKiWithCardIDData:(NSData *)cardIdData withIMSIData:(NSData *)imsiData{
    //主命令
    self.mCmd=0x02;
    //子令命
    self.subCmd=0x01;
    
    self.cardData=cardIdData;
    
    //命令参数
    NSMutableData *mulData=[NSMutableData dataWithCapacity:1024];
    Byte b[2];
    b[0]=0x00;
    b[1]=(Byte)(imsiData.length&0xff);
    [mulData appendBytes:b length:2];
    [mulData appendData:imsiData];
    
    self.cmdData=mulData;
    
    NSUInteger uLen=self.packSN.length+self.apkSN.length+self.appSN.length+mulData.length;
    
    //数据区长度
    self.udataPackLen=uLen;
    
    //总包长度
    self.totalDataPackLen=[self GetPartShortDataPack].length+[self GetCmdDataPack].length+[self GetAllDataAreaDataPack].length;
}

/**
 *  判断是否为释放ki
 *
 *  @return YES:是 NO:不是
 */
- (BOOL)isReleaseKiData{

    if (self.mCmd==0x02&&self.subCmd==0x01) {
        return YES;
    }
    return NO;
}

/**
 *  判断ki是否下载成功
 *
 *  @return
 */
- (BOOL)success{

    if (self.stateData&&[self.stateData length]>0) {
        
        Byte *b=(Byte *)[self.stateData bytes];
        if (self.stateData.length>=2&&b[0]==0x00&&b[1]==0x00) {
            return YES;
        }
    }
    return NO;
}

/**
 *  取得ki数据
 *
 *  @return
 */
- (NSData *)GetKiData{

    if (self.cmdData&&[self.cmdData length]>0) {
        
        Byte *b=(Byte *)[self.cmdData bytes];
        int len=b[2]&0xff;
        //NSLog(@"ki数据数据长度：%d",len);
        //NSLog(@"ki数据数据：%@",[self.cmdData subdataWithRange:NSMakeRange(self.cmdData.length-len, len)]);
        return [self.cmdData subdataWithRange:NSMakeRange(self.cmdData.length-len, len)];
    }

    return nil;
}

#pragma mark -私有方法

/**
 *  (1)短包区
 *
 *  @return 
 */
- (NSData *)GetAllShortDataPack{

    NSMutableData *shortData=[NSMutableData dataWithCapacity:1024];
    
    //总的数据长度
    /**
    NSInteger totalLen=NSSwapHostIntToBig((int)self.totalDataPackLen);
    NSData *totalData = [NSData dataWithBytes:&totalLen length:4];
    [shortData appendData:totalData];
     **/
    [self writeShort:shortData value:self.totalDataPackLen];
    
    [shortData appendData:[self GetPartShortDataPack]];
    
    //打印日志
    [self writeLogWithData:shortData logName:@"短包区"];
    
    return shortData;
    
}
- (NSData *)GetPartShortDataPack{

    //(1)短包区
    NSMutableData *shortData=[NSMutableData dataWithCapacity:1024];
    
    //总的数据长度PKL
    
    //FLAG1
    Byte b[1];
    b[0]=self.packVersion;
    [shortData appendBytes:b length:1];
    
    //FLAG2
    b[0]=self.ascSign;
    [shortData appendBytes:b length:1];
    
    return shortData;
}

/**
 *  (2)取得命令区
 *
 *  @return
 */
- (NSData *)GetCmdDataPack{

    NSMutableData *cmdData=[NSMutableData dataWithCapacity:1024];
    //card id
    [cmdData appendData:self.cardData];
    
    Byte b[1];
    //cmd1
    b[0]=self.mCmd;
    [cmdData appendBytes:b length:1];
    //cmd2
    b[0]=self.subCmd;
    [cmdData appendBytes:b length:1];
    
    //打印日志
    [self writeLogWithData:cmdData logName:@"命令区"];
    
    return cmdData;
}

/**
 *  (3)取得部份数据区
 *
 *  @return
 */
- (NSData *)GetPartDataAreaDataPack{

    NSMutableData *mulData=[NSMutableData dataWithCapacity:1024];
    [mulData appendData:self.packSN];
    [mulData appendData:self.apkSN];
    [mulData appendData:self.appSN];
    [mulData appendData:self.cmdData];
    
    //打印日志
    [self writeLogWithData:mulData logName:@"数据区"];
    
    return mulData;
}

/**
 *  (4)取得数据区+mac区＋UDL
 *
 *  @return
 */
- (NSData *)GetAllDataAreaDataPack{
    
    NSMutableData *mulData=[NSMutableData dataWithCapacity:1024];
    
    //数据区长度
    /**
    short nLen = NSSwapHostShortToBig((int)self.udataPackLen);
    NSData *UDLLen = [NSData dataWithBytes:&nLen length:2];
     [mulData appendData:UDLLen];
     **/
    [self writeShort:mulData value:self.udataPackLen];

    //数据区
    [mulData appendData:[self GetPartDataAreaDataPack]];
    //mac区
    [mulData appendData:self.macData];
    
    return mulData;
}

- (void)writeShort:(NSMutableData *)data value:(NSUInteger)aValue{

    short nLen = NSSwapHostShortToBig((int)aValue);
    NSData *dataLen = [NSData dataWithBytes:&nLen length:2];
    [self writeLogWithData:dataLen logName:@"写入数据长度为"];
    [data appendData:dataLen];
}


- (void)writeLogWithData:(NSData *)data logName:(NSString *)name{
    Byte *bufBytes=(Byte *)[data bytes];
    NSMutableString * hexString = [[NSMutableString alloc] init];
    for(NSUInteger i = 0; i <data.length; i++ )
        [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", bufBytes[i]]];
    
    //NSLog(@"%@命令 =%@",name,hexString);
}

@end
